<?php

/**
 * 多站点标签工具（不依赖wp-load.php，支持动态表前缀）
 */

// 1. 加载数据库配置（建议改为从外部配置文件读取）
$config = [
    'DB_HOST' => 'localhost',
    'DB_USER' => 'root',
    'DB_PASSWORD' => '123465',
    'DB_NAME' => 'wp',
    'TABLE_PREFIX' => 'wp_6_'
];

// 2. 连接数据库
$db = new mysqli($config['DB_HOST'], $config['DB_USER'], $config['DB_PASSWORD'], $config['DB_NAME']);
if ($db->connect_error) {
    die("数据库连接失败: " . $db->connect_error);
}
$db->set_charset("utf8mb4");

/**
 * 为WordPress分站中标签数量少于5个的文章批量分配新标签。
 *
 * @param mysqli $db 数据库连接实例。
 * @param string $prefix 目标分站的数据表前缀。
 * @param int $total_to_process 总共希望处理的文章数量。
 * @param int $batch_size 每批处理的文章数量。
 */
function assign_tags_to_posts($db, $prefix, $total_to_process = 500, $batch_size = 100)
{
    // 设置脚本最大执行时间，防止超时
    set_time_limit(0);
    echo "<pre>";
    echo "开始为站点 {$prefix} 的文章分配标签...\n";

    // 1. 获取所有未被任何文章使用的 post_tag (count = 0)
    $tag_taxonomy_ids = [];
    $sql_get_tags = "SELECT term_taxonomy_id FROM {$prefix}term_taxonomy WHERE taxonomy = 'post_tag' ORDER BY count ASC limit 1000";
    $result = $db->query($sql_get_tags);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $tag_taxonomy_ids[] = $row['term_taxonomy_id'];
        }
        $result->free();
    } else {
        echo "错误: 未能找到任何未使用的标签，无法继续执行。\n";
        echo "</pre>";
        return;
    }
    echo "共找到 " . count($tag_taxonomy_ids) . " 个未使用的标签可供分配。\n\n";

    $processed_count = 0;
    while ($processed_count < $total_to_process) {
        $limit = min($batch_size, $total_to_process - $processed_count);

        // 2. 分页获取关联标签少于5个的文章ID
        $post_ids = [];
        $sql_get_posts = "
            SELECT p.ID
            FROM {$prefix}posts p
            WHERE p.post_type = 'post'
            AND p.post_status = 'publish'
            AND (
                SELECT COUNT(*)
                FROM {$prefix}term_relationships tr
                JOIN {$prefix}term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                WHERE tr.object_id = p.ID AND tt.taxonomy = 'post_tag'
            ) < 5
            ORDER BY p.ID DESC
            LIMIT " . (int)$limit;

        $result = $db->query($sql_get_posts);
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $post_ids[] = $row['ID'];
            }
            $result->free();
        } else {
            echo "已没有关联标签少于5个的文章了。\n";
            break; // 结束循环
        }

        echo "本批次找到 " . count($post_ids) . " 篇标签不足的文章进行处理...\n";

        // 3. 为每篇文章清空旧标签，并分配5-10个新的随机标签
        $delete_sql = "
            DELETE tr FROM {$prefix}term_relationships tr
            JOIN {$prefix}term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
            WHERE tr.object_id = ? AND tt.taxonomy = 'post_tag'
        ";
        $delete_stmt = $db->prepare($delete_sql);
        $insert_stmt = $db->prepare("INSERT INTO {$prefix}term_relationships (object_id, term_taxonomy_id) VALUES (?, ?)");

        if (!$delete_stmt || !$insert_stmt) {
            die("数据库语句准备失败: " . $db->error);
        }

        shuffle($post_ids);
        foreach ($post_ids as $post_id) {
            // a. 清除该文章现有的 post_tag 关系
            $delete_stmt->bind_param('i', $post_id);
            $delete_stmt->execute();

            // b. 从闲置标签池中随机选择5-10个新标签并插入
            $num_tags_to_assign = rand(5, 10);
            $selected_tag_ids = [];
            $tag_index = 0;

            while (count($selected_tag_ids) < $num_tags_to_assign && $tag_index < count($tag_taxonomy_ids)) {
                $selected_tag_ids[] = $tag_taxonomy_ids[$tag_index];
                $tag_index++;
            }

            foreach ($selected_tag_ids as $tag_taxonomy_id) {
                $insert_stmt->bind_param('ii', $post_id, $tag_taxonomy_id);
                $insert_stmt->execute();
            }
        }
        $delete_stmt->close();
        $insert_stmt->close();

        $processed_count += count($post_ids);
        echo "本批次处理完成。已处理文章总数: {$processed_count} / {$total_to_process}\n\n";
        flush(); // 将输出发送到浏览器
    }


    // 4. 重新计算所有标签的计数
    echo "正在重新计算所有标签的计数...\n";
    $recount_sql = "
        UPDATE {$prefix}term_taxonomy tt
        SET count = (
            SELECT COUNT(tr.object_id)
            FROM {$prefix}term_relationships tr
            JOIN {$prefix}posts p ON tr.object_id = p.ID
            WHERE tr.term_taxonomy_id = tt.term_taxonomy_id
            AND p.post_status = 'publish'
            AND p.post_type = 'post'
        )
        WHERE tt.taxonomy = 'post_tag'";

    if ($db->query($recount_sql)) {
        echo "标签计数更新成功。\n";
    } else {
        echo "错误: 更新标签计数失败 - " . $db->error . "\n";
    }

    echo "\n任务完成！\n";
    echo "</pre>";
}

// 执行分配，处理500篇标签不足的文章，每批100篇
assign_tags_to_posts($db, $config['TABLE_PREFIX'], 10000, 100);

$db->close();

exit;
